<template>
    <div>
        <!-- 面包屑导航 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>角色列表</el-breadcrumb-item>
            <el-breadcrumb-item>权限列表</el-breadcrumb-item>
        </el-breadcrumb>
        <!-- 卡片信息 -->
        <el-card>
            <!-- 添加按钮 -->
            <el-row>
                <el-col>
                    <el-button type="primary" @click="addDialogFormVisible = true">添加角色</el-button>
                </el-col>
            </el-row>
            <!-- 角色权限表单 -->
            <el-table :data="rolesList" stripe border>
                <el-table-column type="expand">
                  <template slot-scope="scope">
                    <el-row v-for="(item1,i1) in scope.row.children" :key="item1.id" :class="['bdbottom', i1 === 0 ? 'bdtop':'','vcenter']">
                      <!-- 第一级 -->
                      <el-col :span="5">
                        <el-tag closable @close="removeRights(scope.row,item1.id)">{{item1.authName}}</el-tag>
                        <i class="el-icon-caret-right"></i>
                      </el-col>
                      <!-- 第二级 -->
                      <el-col :span="19">
                        <el-row v-for="(item2,i2) in item1.children" :key="item2.id" :class="[i2 === 0 ? '':'bdtop','vcenter']">
                          <el-col :span='6'>
                            <el-tag type="success" closable @close="removeRights(scope.row,item2.id)">{{item2.authName}}</el-tag>
                            <i class="el-icon-caret-right"></i>
                          </el-col>
                          <el-col :span='18'>
                            <el-tag v-for="item3 in item2.children" :key="item3.id" type="warning" closable @close="removeRights(scope.row,item3.id)">{{item3.authName}}</el-tag>
                          </el-col>
                        </el-row>
                      </el-col>
                    </el-row>
                  </template>
                </el-table-column>
                <el-table-column type="index" label="#"></el-table-column>
                <el-table-column label="角色名称" prop='roleName'></el-table-column>
                <el-table-column label="角色描述" prop='roleDesc'></el-table-column>
                <el-table-column label="操作" width="450px">
                    <template slot-scope="scope">
                        <el-button type="primary" icon="el-icon-edit" @click="modifyRoles(scope.row.id)">编辑</el-button>
                        <el-button type="danger" icon="el-icon-delete" @click="removeRoles(scope.row.id)">删除</el-button>
                        <el-button type="warning" icon="el-icon-setting" @click="showSetRightDialog(scope.row)">权限管理</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-card>

        <!-- 添加角色对话框 -->
        <el-dialog title="添加角色" :visible.sync="addDialogFormVisible" @close="closeInfo">
            <el-form :model="addForm" status-icon :rules="addFormRules" ref="addFormRef" label-width="100px">
                <el-form-item label="角色名称" prop="roleName">
                    <el-input v-model="addForm.roleName"></el-input>
                </el-form-item>
                <el-form-item label="角色描述">
                    <el-input v-model="addForm.roleDesc"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="addDialogFormVisible = false">取 消</el-button>
                <el-button type="primary" @click="addNewRoles">确 定</el-button>
            </div>
        </el-dialog>

        <!-- 修改角色对话框 -->
        <el-dialog title="修改角色" :visible.sync="modifyDialogForm" @close="closeModifyInfo" width="50%">
            <el-form :model="modifyInfo" status-icon :rules="modifyFormRules" ref="modifyFormRef" label-width="100px">
                <el-form-item label="角色名称" prop="roleName">
                    <el-input v-model="modifyInfo.roleName"></el-input>
                </el-form-item>
                <el-form-item label="角色描述">
                    <el-input v-model="modifyInfo.roleDesc"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="modifyDialogForm = false">取 消</el-button>
                <el-button type="primary" @click="modifyNewRoles">确 定</el-button>
            </div>
        </el-dialog>
        <!-- 权限管理对话框 -->
        <el-dialog title="权限管理" :visible.sync="showRightDialogVisible" width="50%" @close="emptyRightsKeys">
          <!-- 树形结构 -->
          <el-tree show-checkbox :data="rightsList" :props="defaultInfo" node-key="id" default-expand-all :default-checked-keys="defaultKeys" ref="treeRef"></el-tree>
          <span slot="footer" class="dialog-footer">
            <el-button @click="showRightDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="distributeRight">确 定</el-button>
          </span>
        </el-dialog>
    </div>
</template>

<script>
export default {
  data() {
    return {
      // 角色列表
      rolesList: [],
      // 是否显示对话框
      addDialogFormVisible: false,
      // 添加角色列表
      addForm: {
        roleName: '',
        roleDesc: ''
      },
      addFormRules: {
        roleName: [{ required: true, message: '请输入角色名称', trigger: 'blur' }, {
          min: 2,
          max: 10,
          message: '长度在 2 到 10 个字符',
          trigger: 'blur'
        }]
      },
      modifyFormRules: {
        roleName: [{ required: true, message: '请输入角色名称', trigger: 'blur' }, {
          min: 2,
          max: 10,
          message: '长度在 2 到 10 个字符',
          trigger: 'blur'
        }]
      },
      // 是否显示对话框
      modifyDialogForm: false,
      //   要被修改角色信息
      modifyInfo: {},
      // 是否显示权限管理对话框
      showRightDialogVisible: false,
      // 权限管理列表
      rightsList: {},
      // 树形结构配置
      defaultInfo: {
        label: 'authName',
        children: 'children'
      },
      // 权限ID
      defaultKeys: [116, 124],
      // 要分配角色的Id
      roleId: ''
    }
  },
  created() {
    this.getRolesList()
  },
  methods: {
    //   获取角色列表
    async getRolesList() {
      const { data: res } = await this.$http.get('/roles')
      if (res.meta.status !== 200) {
        return this.$message({
          showClose: true,
          message: '获取角色列表失败',
          type: 'error'
        })
      }
      this.rolesList = res.data
    },
    // 清楚添加角色表单
    closeInfo() {
      this.$refs.addFormRef.resetFields()
    },
    // 添加角色
    addNewRoles() {
      this.$refs.addFormRef.validate(async val => {
        if (!val) {
          return this.$message({
            showClose: true,
            message: '添加角色失败！',
            type: 'error'
          })
        }
        // 发送网络请求
        const { data: res } = await this.$http.post('roles', this.addForm)
        if (res.meta.status !== 201) {
          return this.$message({
            showClose: true,
            message: '添加角色失败！',
            type: 'error'
          })
        }
        this.getRolesList()
        this.$message({
          showClose: true,
          message: '添加角色成功！',
          type: 'success'
        })
        this.addDialogFormVisible = false
      })
    },
    // 获取修改角色信息
    async modifyRoles(id) {
      this.modifyDialogForm = true
      const { data: res } = await this.$http.get('/roles/' + id)
      if (res.meta.status !== 200) {
        return this.$message({
          showClose: true,
          message: '获取该角色失败！',
          type: 'error'
        })
      }
      this.modifyInfo = res.data
    },
    // 清除对话框信息
    closeModifyInfo() {
      this.$refs.modifyFormRef.resetFields()
    },
    // 修改角色
    modifyNewRoles() {
      this.$refs.modifyFormRef.validate(async val => {
        if (!val) {
          return this.$message({
            showClose: true,
            message: '表单验证失败！',
            type: 'error'
          })
        }
        const { data: res } = await this.$http.put('/roles/' + this.modifyInfo.roleId, {
          roleName: this.modifyInfo.roleName,
          roleDesc: this.modifyInfo.roleDesc
        })
        console.log(res)
        if (res.meta.status !== 200) {
          return this.$message({
            showClose: true,
            message: '修改角色失败！',
            type: 'error'
          })
        }
        this.getRolesList()
        this.$message({
          showClose: true,
          message: '修改角色成功！',
          type: 'success'
        })
        this.modifyDialogForm = false
      })
    },
    // 删除角色
    async removeRoles(id) {
      const removeInfo = await this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (removeInfo !== 'confirm') {
        return this.$message({
          showClose: true,
          message: '删除用户操作已取消！',
          type: 'info'
        })
      } else {
        const { data: res } = await this.$http.delete('/roles/' + id)
        if (res.meta.status !== 200) {
          return this.$message({
            showClose: true,
            message: res.meta.msg,
            type: 'error'
          })
        }
        this.getRolesList()
        this.$message({
          showClose: true,
          message: '删除用户成功！',
          type: 'success'
        })
      }
    },
    // 删除权限
    async removeRights(role, rightId) {
      const removeInfo = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (removeInfo !== 'confirm') {
        return this.$message({
          showClose: true,
          message: '删除权限操作已取消！',
          type: 'info'
        })
      } else {
        const { data: res } = await this.$http.delete(`roles/${role.id}/rights/${rightId}`)
        if (res.meta.status !== 200) {
          return this.$message({
            showClose: true,
            message: res.meta.msg,
            type: 'error'
          })
        }
        role.children = res.data
      }
    },
    // 展现权限树形对话框
    async showSetRightDialog(role) {
      this.roleId = role.id
      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) {
        return this.$message({
          showClose: true,
          message: '获取角色权限失败！',
          type: 'error'
        })
      }
      this.getLeafKeys(role, this.defaultKeys)
      this.rightsList = res.data
      this.showRightDialogVisible = true
    },
    // 递归循环出id
    getLeafKeys(node, arr) {
      if (!node.children) {
        return arr.push(node.id)
      }
      node.children.forEach(element => {
        this.getLeafKeys(element, arr)
      })
    },
    // 关闭对话框清空树形复选框
    emptyRightsKeys() {
      this.defaultKeys = []
    },
    // 分配角色
    async distributeRight() {
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      const Idkeys = keys.join(',')
      const { data: res } = await this.$http.post(`/roles/${this.roleId}/rights`, { rids: Idkeys })
      if (res.meta.status !== 200) {
        return this.$message({
          showClose: true,
          message: '角色列表分配失败！',
          type: 'error'
        })
      }
      this.$message({
        showClose: true,
        message: '角色分配成功！',
        type: 'success'
      })
      this.getRolesList()
      this.showRightDialogVisible = false
    }
  }
}
</script>

<style lang="less" scoped>
.el-table{
    margin-top: 20px;
}
.el-tag{
  margin: 7px;
}
.bdtop{
  border-top: 1px solid #eee;
}
.bdbottom{
  border-bottom: 1px solid #eee;
}
.vcenter{
  display: flex;
  align-items: center;
}
</style>
